<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <!-- Loading State -->
      <div v-if="loading" class="text-center py-12">
        <Loader2 class="w-8 h-8 animate-spin text-primary-600 mx-auto mb-4" />
        <p class="text-gray-600">加载会议详情...</p>
      </div>

      <!-- Meeting Content -->
      <div v-else-if="meeting">
        <!-- Header -->
        <div class="card p-6 mb-8">
          <div class="flex items-start justify-between">
            <div>
              <div class="flex items-center gap-3 mb-4">
                <router-link
                  to="/history"
                  class="text-gray-600 hover:text-gray-900 p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <ArrowLeft class="w-5 h-5" />
                </router-link>
                <h1 class="text-3xl font-bold text-gray-900">{{ meeting.title }}</h1>
                <div
                  class="px-3 py-1 text-sm rounded-full"
                  :class="getStatusClass(meeting.status)"
                >
                  {{ getStatusText(meeting.status) }}
                </div>
              </div>

              <p v-if="meeting.description" class="text-gray-600 mb-4">
                {{ meeting.description }}
              </p>

              <div class="flex flex-wrap gap-6 text-sm text-gray-500">
                <div class="flex items-center gap-2">
                  <Calendar class="w-4 h-4" />
                  <span>{{ formatDate(meeting.created_at) }}</span>
                </div>

                <div v-if="meeting.duration" class="flex items-center gap-2">
                  <Clock class="w-4 h-4" />
                  <span>{{ formatDuration(meeting.duration) }}</span>
                </div>

                <div v-if="meeting.updated_at" class="flex items-center gap-2">
                  <Edit class="w-4 h-4" />
                  <span>更新于 {{ formatDate(meeting.updated_at) }}</span>
                </div>
              </div>
            </div>

            <div class="flex items-center gap-2">
              <button
                @click="deleteMeeting"
                class="text-red-600 hover:text-red-700 p-2 hover:bg-red-50 rounded-lg transition-colors"
              >
                <Trash2 class="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>

        <!-- Tabs -->
        <div class="border-b border-gray-200 mb-8">
          <nav class="flex space-x-8">
            <button
              v-for="tab in tabs"
              :key="tab.key"
              @click="activeTab = tab.key"
              class="py-2 px-1 border-b-2 font-medium text-sm transition-colors"
              :class="{
                'border-primary-500 text-primary-600': activeTab === tab.key,
                'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== tab.key
              }"
            >
              <div class="flex items-center gap-2">
                <component :is="tab.icon" class="w-4 h-4" />
                {{ tab.label }}
                <span v-if="tab.count" class="bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full text-xs">
                  {{ tab.count }}
                </span>
              </div>
            </button>
          </nav>
        </div>

        <!-- Tab Content -->
        <div class="space-y-8">
          <!-- Transcripts Tab -->
          <div v-if="activeTab === 'transcripts'">
            <div class="card">
              <div class="p-6 border-b border-gray-200">
                <div class="flex items-center justify-between">
                  <h2 class="text-lg font-semibold text-gray-900">转录内容</h2>
                  <div class="flex items-center gap-2">
                    <button
                      @click="copyAllTranscripts"
                      class="text-primary-600 hover:text-primary-700 p-2 hover:bg-primary-50 rounded-lg transition-colors"
                    >
                      <Copy class="w-5 h-5" />
                    </button>
                  </div>
                </div>
              </div>

              <div v-if="transcripts.length === 0" class="p-12 text-center">
                <FileX class="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <p class="text-gray-500">暂无转录内容</p>
              </div>

              <div v-else class="divide-y divide-gray-200">
                <div
                  v-for="(transcript, index) in transcripts"
                  :key="transcript.id"
                  class="p-6 hover:bg-gray-50 transition-colors"
                >
                  <div class="flex items-start justify-between mb-3">
                    <div class="flex items-center gap-3">
                      <span class="text-sm font-medium text-gray-500">#{{ index + 1 }}</span>
                      <span v-if="transcript.speaker" class="text-sm font-medium text-primary-600">
                        {{ transcript.speaker }}
                      </span>
                      <span class="text-sm text-gray-500">
                        {{ formatTimestamp(transcript.timestamp) }}
                      </span>
                    </div>
                    <div v-if="transcript.confidence" class="text-sm text-gray-500">
                      置信度: {{ (transcript.confidence * 100).toFixed(1) }}%
                    </div>
                  </div>
                  <p class="text-gray-900 leading-relaxed">{{ transcript.text }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- Minutes Tab -->
          <div v-if="activeTab === 'minutes'">
            <div class="card">
              <div class="p-6 border-b border-gray-200">
                <div class="flex items-center justify-between">
                  <h2 class="text-lg font-semibold text-gray-900">会议纪要</h2>
                  <div class="flex items-center gap-2">
                    <button
                      v-if="!editingMinutes"
                      @click="startEditingMinutes"
                      class="text-primary-600 hover:text-primary-700 p-2 hover:bg-primary-50 rounded-lg transition-colors"
                    >
                      <Edit class="w-5 h-5" />
                    </button>
                    <button
                      v-if="editingMinutes"
                      @click="saveMinutes"
                      class="text-primary-600 hover:text-primary-700 p-2 hover:bg-primary-50 rounded-lg transition-colors"
                    >
                      <Check class="w-5 h-5" />
                    </button>
                    <button
                      v-if="editingMinutes"
                      @click="cancelEditingMinutes"
                      class="text-gray-600 hover:text-gray-700 p-2 hover:bg-gray-50 rounded-lg transition-colors"
                    >
                      <X class="w-5 h-5" />
                    </button>
                    <button
                      @click="exportMinutes"
                      class="text-primary-600 hover:text-primary-700 p-2 hover:bg-primary-50 rounded-lg transition-colors"
                    >
                      <Download class="w-5 h-5" />
                    </button>
                    <button
                      v-if="!minutes"
                      @click="generateMinutes"
                      :disabled="generatingMinutes"
                      class="btn-primary text-sm px-4 py-2"
                    >
                      {{ generatingMinutes ? '生成中...' : '生成纪要' }}
                    </button>
                  </div>
                </div>
              </div>

              <div class="p-6">
                <div v-if="generatingMinutes" class="text-center py-12">
                  <Loader2 class="w-8 h-8 animate-spin text-primary-600 mx-auto mb-4" />
                  <p class="text-gray-600">正在生成会议纪要...</p>
                </div>

                <div v-else-if="!minutes" class="text-center py-12">
                  <FileText class="w-16 h-16 text-gray-300 mx-auto mb-4" />
                  <p class="text-gray-500 mb-6">暂无会议纪要</p>
                  <button
                    @click="generateMinutes"
                    :disabled="generatingMinutes"
                    class="btn-primary"
                  >
                    {{ generatingMinutes ? '生成中...' : '生成纪要' }}
                  </button>
                </div>

                <div v-else>
                  <!-- View Mode -->
                  <div v-if="!editingMinutes">
                    <MarkdownRenderer :content="minutes.content || ''" />
                  </div>

                  <!-- Edit Mode -->
                  <div v-else>
                    <textarea
                      v-model="editingMinutesContent"
                      class="w-full h-96 p-4 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent resize-none font-mono text-sm"
                      placeholder="编辑会议纪要..."
                    ></textarea>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Audio Tab -->
          <div v-if="activeTab === 'audio'">
            <div class="card p-6">
              <h2 class="text-lg font-semibold text-gray-900 mb-6">音频播放</h2>

              <div v-if="!audioUrl" class="text-center py-12">
                <FileAudio class="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <p class="text-gray-500">暂无音频文件</p>
              </div>

              <div v-else>
                <audio controls class="w-full mb-4">
                  <source :src="audioUrl" type="audio/wav">
                  您的浏览器不支持音频播放
                </audio>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Not Found -->
      <div v-else class="text-center py-12">
        <FileX class="w-16 h-16 text-gray-300 mx-auto mb-4" />
        <h2 class="text-2xl font-semibold text-gray-900 mb-2">会议不存在</h2>
        <p class="text-gray-600 mb-6">您要查找的会议不存在或已被删除</p>
        <router-link to="/history" class="btn-primary">
          返回历史记录
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMeetingStore } from '@/stores/meeting'
import { generateMinutes as generateMinutesApi, updateMinutes } from '@/services/api'
import type { Meeting, Transcript, Minutes } from '@/types'
import MarkdownRenderer from '@/components/ui/MarkdownRenderer.vue'
import {
  ArrowLeft,
  Calendar,
  Clock,
  Edit,
  Trash2,
  Copy,
  Download,
  FileX,
  FileText,
  FileAudio,
  Loader2,
  Check,
  X
} from 'lucide-vue-next'

const route = useRoute()
const router = useRouter()
const meetingStore = useMeetingStore()

const meetingId = computed(() => route.params.id as string)
const meeting = computed(() => meetingStore.currentMeeting)
const transcripts = computed(() => meetingStore.transcripts)
const minutes = computed(() => meetingStore.currentMinutes)

// UI State
const loading = ref(true)
const activeTab = ref('transcripts')
const generatingMinutes = ref(false)
const editingMinutes = ref(false)
const editingMinutesContent = ref('')
const audioUrl = ref<string>()

// Tabs
const tabs = computed(() => [
  {
    key: 'transcripts',
    label: '转录内容',
    icon: FileText,
    count: transcripts.value.length
  },
  {
    key: 'minutes',
    label: '会议纪要',
    icon: FileText,
    count: minutes.value ? 1 : 0
  },
  {
    key: 'audio',
    label: '音频',
    icon: FileAudio,
    count: 0
  }
])

// Methods
const loadMeeting = async () => {
  try {
    loading.value = true
    await meetingStore.fetchMeeting(meetingId.value)
  } catch (error) {
    console.error('Failed to load meeting:', error)
  } finally {
    loading.value = false
  }
}

const deleteMeeting = async () => {
  if (confirm('确定要删除这个会议吗？此操作不可撤销。')) {
    try {
      await meetingStore.removeMeeting(meetingId.value)
      router.push('/history')
    } catch (error) {
      console.error('Failed to delete meeting:', error)
    }
  }
}

const generateMinutes = async () => {
  try {
    generatingMinutes.value = true
    const result = await generateMinutesApi(meetingId.value, 'default')
    meetingStore.updateMinutes(result)
  } catch (error) {
    console.error('Failed to generate minutes:', error)
  } finally {
    generatingMinutes.value = false
  }
}

const startEditingMinutes = () => {
  editingMinutes.value = true
  editingMinutesContent.value = minutes.value?.content || ''
}

const saveMinutes = async () => {
  try {
    const result = await updateMinutes(meetingId.value, editingMinutesContent.value)
    meetingStore.updateMinutes(result)
    editingMinutes.value = false
  } catch (error) {
    console.error('Failed to save minutes:', error)
  }
}

const cancelEditingMinutes = () => {
  editingMinutes.value = false
  editingMinutesContent.value = minutes.value?.content || ''
}

const copyAllTranscripts = async () => {
  const text = transcripts.value.map(t => t.text).join('\n\n')
  await navigator.clipboard.writeText(text)
  // TODO: Show toast notification
}

const exportMinutes = () => {
  if (minutes.value?.content) {
    const blob = new Blob([minutes.value.content], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `meeting-minutes-${new Date().toISOString().split('T')[0]}.md`
    a.click()
    URL.revokeObjectURL(url)
  }
}

const getStatusClass = (status: string) => {
  switch (status) {
    case 'recording':
      return 'bg-red-100 text-red-800'
    case 'processing':
      return 'bg-yellow-100 text-yellow-800'
    case 'completed':
      return 'bg-green-100 text-green-800'
    default:
      return 'bg-gray-100 text-gray-800'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'recording':
      return '录音中'
    case 'processing':
      return '处理中'
    case 'completed':
      return '已完成'
    default:
      return '未知'
  }
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

const formatTimestamp = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

onMounted(() => {
  loadMeeting()
})
</script>